from flask import Blueprint, request, jsonify
from flask_cors import CORS
import json
from RealProject.db_init import db, Model, session
from app.datafactory.dao import ProjectDao, ReqinfoDao,ScriptDao,CustomFuncDao
from app.utils import obj_to_dict
from .core import Harparser
from .ReqParser import Reqparser
# URL会自动加上url_prefix的值
DATAFACTORY_URL_PREFIX = '/datafactory'
datafactory_bp = Blueprint('datafactory', __name__, url_prefix=DATAFACTORY_URL_PREFIX)
CORS(datafactory_bp, supports_credentials=True)
project_dao = ProjectDao()
req_dao = ReqinfoDao()
script_dao = ScriptDao()
custom_func_dao = CustomFuncDao()

# 获取项目信息
@datafactory_bp.route('/project/<int:project_id>', methods=['GET'])
def get_project(project_id):
    """
    获取指定项目的信息

    Args:
        project_id: 项目ID

    Returns:
        包含项目信息的JSON对象
    """
    project = project_dao.get_project(project_id)
    print(project)
    if not project:
        return jsonify({'code': 400, 'msg': '项目不存在'})
    return jsonify({'code': 200, "data": project})

# 获取项目列表信息
@datafactory_bp.route('/project', methods=['GET'])
def get_project_list():
    """
    获取项目列表信息

    Returns:
        包含项目列表信息的JSON对象
    """

    page_num = request.args.get('pageNum')
    page_size = request.args.get('pageSize')

    total, project_list = project_dao.get_projects(page_num, page_size)
    if total == 0:
        return jsonify({'code': 200, "data": {"records": [], "total": total}})
    else:
        projects = obj_to_dict(project_list.items)
        return jsonify({'code': 200, "data": {"records": projects, "total": total}})

# 创建项目
@datafactory_bp.route('/project', methods=['POST'])
def create_project():
    """
    创建项目

    Returns:
        包含操作结果的JSON对象
    """
    project_name = request.json.get('name')
    if not project_name:
        return jsonify({'code': 400, 'msg': '缺少参数：项目名称'})
    if project_dao.name_duplicate(project_name):
        return jsonify({'code': 400, 'msg': '项目名称重复'})
    project_desc = request.json.get('description')
    project = project_dao.create_project(project_name, project_desc)
    if not project:
        return jsonify({'code': 400, 'msg': '创建失败'})
    return jsonify({'code': 200, 'msg': '创建成功'})

# 修改项目
@datafactory_bp.route('/project/<int:project_id>', methods=['PUT'])
def update_project(project_id):
    """
    修改项目

    Args:
        project_id: 项目ID

    Returns:
        包含操作结果的JSON对象
    """
    project_new_name = request.json.get('name')
    if not project_new_name:
        return jsonify({'code': 400, 'msg': '缺少参数：项目名称'})
    project_name = project_dao.get_project(project_id).get('name')
    if project_new_name != project_name and project_dao.name_duplicate(project_new_name):
        return jsonify({'code': 400, 'msg': '项目名称重复'})
    project_desc = request.json.get('description')
    project = project_dao.update_project(project_id, project_new_name, project_desc)
    if not project:
        return jsonify({'code': 400, 'msg': '项目不存在'})
    return jsonify({'code': 200, 'msg': '修改成功'})

# 删除项目
@datafactory_bp.route('/project/<int:project_id>', methods=['DELETE'])
def del_project(project_id):
    """
    删除项目

    Args:
        project_id: 项目ID

    Returns:
        包含操作结果的JSON对象
    """
    project = project_dao.delete_project(project_id)
    if not project:
        return jsonify({'code': 400, 'msg': '项目不存在'})
    return jsonify({'code': 200, 'msg': '删除成功'})

# 解析Har文件
@datafactory_bp.route('/harupload', methods=['POST'])
def analysis_har_file():
    """
    解析Har文件

    Returns:
        包含解析结果的JSON对象
    """
    har_file = request.files.get('file')
    if not har_file:
        return jsonify({'code': 400, 'msg': '未上传文件'})
    content = har_file.read()
    request_list = Harparser().har_reuqest(json.loads(content))
    response_data = {
        "code": 200,
        "msg": "解析成功",
        "data": request_list
    }
    return jsonify(response_data)

# 添加请求信息
@datafactory_bp.route('/scriptmanage/reqinfo', methods=['POST'])
def add_reqinfo():
    """
    添加请求信息

    Returns:
        包含操作结果的JSON对象
    """
    title = request.json.get('title')

    if not title:
        return jsonify({'code': 400, 'msg': '缺少参数：标题'})
    if req_dao.name_duplicate(title):
        return jsonify({'code': 400, 'msg': '该请求列表已存在'})
    req_info_list = request.json.get('data')



    if not req_info_list:
        return jsonify({'code': 400, 'msg': '缺少参数：请求信息'})
    reqlist = req_dao.create_ReqInfo(req_info_list, title)
    if not reqlist:
        return jsonify({'code': 400, 'msg': '新增失败'})
    return jsonify({"code": 200, "msg": "新增成功"})

# 获取请求信息列表
@datafactory_bp.route('/scriptmanage/reqinfo', methods=['GET'])
def get_reqinfo_list():
    """
    获取请求信息列表

    Returns:
        包含请求信息列表的JSON对象
    """
    page_num = request.args.get('pageNum')
    page_size = request.args.get('pageSize')
    total, req_info_list = req_dao.get_ReqInfo_list(page_num, page_size)
    if total == 0:
        return jsonify({'code': 200, "data": {"records": [], "total": total}})
    else:
        req_info = obj_to_dict(req_info_list.items)
        return jsonify({'code': 200, "data": {"records": req_info, "total": total}})
@datafactory_bp.route('/scriptmanage/reqinfo/<string:title>', methods=['GET'])
def get_reqinfo(title):
    """
    获取指定请求列表的信息

    Args:
        title: 请求列表标题

    Returns:
        包含项目信息的JSON对象
    """
    reqinfo_list = req_dao.get_ReqInfo(title)
    reqinfo = obj_to_dict(reqinfo_list)
    if not reqinfo:
        return jsonify({'code': 400, 'msg': '请求列表不存在'})
    return jsonify({'code': 200, "data": reqinfo})

@datafactory_bp.route('/scriptmanage/reqinfo/<string:title>', methods=['DELETE'])
def del_reqinfo(title):
    """
    删除请求信息列表

    Args:
        title: 请求列表标题

    Returns:
        包含操作结果的JSON对象
    """
    reqinfo_list = req_dao.delete_ReqInfo(title)
    if not reqinfo_list:
        return jsonify({'code': 400, 'msg': '项目不存在'})
    return jsonify({'code': 200, 'msg': '删除成功'})

# 添加请求信息
@datafactory_bp.route('/scriptmanage/scriptstep', methods=['POST'])
def add_script():
    """
    添加脚本

    Returns:
        包含操作结果的JSON对象
    """
    scriptName = request.json.get('scriptName')
    project_id = request.json.get('project_id')
    if not scriptName or not project_id:
        return jsonify({'code': 400, 'msg': '缺少参数：标题或者项目名称'})
    project =  project_dao.get_project(project_id)
    if not project:
        return jsonify({'code': 400, 'msg': '项目不存在'})
    if script_dao.name_duplicate(project_id,scriptName):
        return jsonify({'code': 400, 'msg': '该脚本已存在'})
    scr = request.json.get('data')

    script_list = Reqparser.make_script(scr)

    if not script_list:
        return jsonify({'code': 400, 'msg': '缺少参数：请求信息'})
    reqlist = script_dao.create_Script(scriptName,script_list, project_id)
    if not reqlist:
        return jsonify({'code': 400, 'msg': '新增失败'})
    return jsonify({"code": 200, "msg": "新增成功"})
@datafactory_bp.route('/scriptmanage/scriptstep/delete', methods=['POST'])
def del_script():
    """
    删除脚本

    Returns:
        包含操作结果的JSON对象
    """
    scriptName = request.json.get('scriptName')
    project_id = request.json.get('project_id')
    if not scriptName or not project_id:
        return jsonify({'code': 400, 'msg': '缺少参数：标题或者项目名称'})
    project =  project_dao.get_project(project_id)
    if not project:
        return jsonify({'code': 400, 'msg': '项目不存在'})



    script= script_dao.delete_Script(project_id,scriptName)
    if not script:
        return jsonify({'code': 400, 'msg': '脚本不存在'})
    return jsonify({'code': 200, 'msg': '删除成功'})


@datafactory_bp.route('/scriptmanage/scriptstep/update', methods=['POST'])
def update_script():
    """
    修建脚本详情

    Returns:
        包含操作结果的JSON对象
    """
    scriptName = request.json.get('scriptName')
    project_id = request.json.get('project_id')
    script_data = request.json.get('data')
    if not scriptName or not project_id:
        return jsonify({'code': 400, 'msg': '缺少参数：标题或者项目名称'})
    project =  project_dao.get_project(project_id)
    if not project:
        return jsonify({'code': 400, 'msg': '项目不存在'})


    script= script_dao.update_Script(project_id, scriptName, script_data)
    if not script:
        return jsonify({'code': 400, 'msg': '脚本不存在'})
    return jsonify({'code': 200, 'msg': '保存成功'})

@datafactory_bp.route('/scriptmanage/scriptstep', methods=['GET'])
def get_script_list():
    """
    查询脚本列表

    Returns:
        包含操作结果的JSON对象
    """
    page_num = request.args.get('pageNum')
    page_size = request.args.get('pageSize')
    total, req_script_list = script_dao.get_Script_list(page_num, page_size)

    if total == 0:
        return jsonify({'code': 200, "data": {"records": [], "total": total}})
    else:
        script_info = obj_to_dict(req_script_list)

        return jsonify({'code': 200, "data": {"records": script_info, "total": total}})


@datafactory_bp.route('/scriptmanage/scriptstep/info', methods=['POST'])
def get_script():
    """
    获取脚本详情

    Returns:
        包含操作结果的JSON对象
    """
    scriptName = request.json.get('scriptName')
    project_id = request.json.get('project_id')
    if not scriptName or not project_id:
        return jsonify({'code': 400, 'msg': '缺少参数：标题或者项目名称'})
    project =  project_dao.get_project(project_id)
    if not project:
        return jsonify({'code': 400, 'msg': '项目不存在'})



    script= script_dao.get_Script(project_id,scriptName)
    print(script)
    scriptinfo = obj_to_dict(script)
    if not scriptinfo:
        return jsonify({'code': 400, 'msg': '脚本不存在'})
    return jsonify({'code': 200, 'data': scriptinfo})

@datafactory_bp.route('/funcmanage/func', methods=['POST'])
def add_customfunc():
    """
    添加函数

    Returns:
        包含操作结果的JSON对象
    """
    FuncName = request.json.get('FuncName')
    FuncBody = request.json.get('FuncBody')
    description = request.json.get('description')
    if not FuncName or not FuncBody:
        return jsonify({'code': 400, 'msg': '缺少参数：函数名或者函数体'})

    if custom_func_dao.name_duplicate(FuncName):
        return jsonify({'code': 400, 'msg': '该自定义函数已存在'})

    customfunc = custom_func_dao.create_customfunc(FuncName,FuncBody,description)
    if not customfunc:
        return jsonify({'code': 400, 'msg': '新增失败'})
    return jsonify({"code": 200, "msg": "新增成功"})

@datafactory_bp.route('/funcmanage/func', methods=['GET'])
def get_customfunc_list():
    """
    查询自定义函数列表

    Returns:
        包含操作结果的JSON对象
    """
    page_num = request.args.get('pageNum')
    page_size = request.args.get('pageSize')
    total, func_list = custom_func_dao.get_CustomFuncs(page_num, page_size)

    if total == 0:
        return jsonify({'code': 200, "data": {"records": [], "total": total}})
    else:
        funcs = obj_to_dict(func_list)

        return jsonify({'code': 200, "data": {"records": funcs, "total": total}})








@datafactory_bp.route('/funcmanage/info', methods=['POST'])
def get_func():
    """
    获取函数详情

    Returns:
        包含操作结果的JSON对象
    """
    FuncName = request.json.get('FuncName')

    if not FuncName :
        return jsonify({'code': 400, 'msg': '缺少参数：函数名称'})


    func= custom_func_dao.get_CustomFunc(FuncName)


    if not func:
        return jsonify({'code': 400, 'msg': '脚本不存在'})
    return jsonify({'code': 200, 'data':func })


@datafactory_bp.route('/funcmanage/func/delete', methods=['POST'])
def del_func():
    """
    删除函数

    Returns:
        包含操作结果的JSON对象
    """
    id = request.json.get('id')
    FuncName = request.json.get('FuncName')

    if not id or not FuncName:
        return jsonify({'code': 400, 'msg': '缺少参数：id或者函数名称'})
    Func =  custom_func_dao.delete_CustomFunc(id, FuncName)




    if not Func:
        return jsonify({'code': 400, 'msg': '函数不存在'})
    return jsonify({'code': 200, 'msg': '删除成功'})





@datafactory_bp.route('/funcmanage/func/update', methods=['POST'])
def update_customfunc():
    """
    修改函数

    Returns:
        包含操作结果的JSON对象
    """
    """
    获取脚本详情

    Returns:
        包含操作结果的JSON对象
    """
    id = request.json.get('id')
    FuncName = request.json.get('FuncName')
    FuncBody  = request.json.get('FuncBody')
    description  = request.json.get('description')
    if not id :
        return jsonify({'code': 400, 'msg': '缺少参数：函数名称'})
    if custom_func_dao.name_duplicate(FuncName):
        return jsonify({'code': 400, 'msg': '该自定义函数已存在'})
    func = custom_func_dao.update_customfunc(id,FuncName,FuncBody,description)

    if not func:
        return jsonify({'code': 400, 'msg': '脚本不存在'})
    return jsonify({'code': 200, 'msg': '保存成功'})
